from django.core.management.base import BaseCommand
from django.db.models import Q, F

from gis.common import track_logging
from gis.common.telegram import send_text_msg_tele
from itpay.core.agency.models import ReceiptAddress
from itpay.core.conf import conf_client
from itpay.core.user.const import UserLevel

_LOGGER = track_logging.getLogger(__name__)


class Command(BaseCommand):
    def handle(self, *args, **options):
        _LOGGER.info("begin check agency receipt")
        try:
            exists = (
                ReceiptAddress.objects.filter(
                    agency_id__in=get_check_agency_ids(),
                    min_user_level=UserLevel.LEVEL_0.value,
                    status=True,
                    deleted=False,
                )
                .filter(
                    Q(daily_amount_limit__isnull=True)
                    | Q(daily_amount__lt=F("daily_amount_limit"))
                )
                .exists()
            )
            if not exists:
                send_text_msg_tele(
                    conf_client.get_value("telegram_group_id"), "当前无免费用户可用收款账号，请及时处理！"
                )

        except Exception:
            _LOGGER.exception("fail check agency receipt")
        _LOGGER.info("end check agency receipt")


def get_check_agency_ids():
    return conf_client.get_dict("our_agency_ids")
